<!-- 治疗任务-处方 -->
<template>
  <div>
    <Dialog :title="title" :visible="visible" :reveal="true" :loading="loading" class="two-columns" @close="handleClose" @confirm="submitForm">
      <div>
        <el-form ref="prescriptionFormRef" :model="prescriptionForm" :rules="prescriptionFormRules" label-position="right" class="formStyles">
          <UserInfo v-if="control" :info-id="prescriptionForm.customerId" class="UserInfoCss" />
          <el-form-item v-else label="顾客：" :prop="control?'':'customerName'" label-width="100px">
            <el-autocomplete v-model="prescriptionForm.customerName" :fetch-suggestions="querySearch" style="width:237.5px" @select="handleSelectCustomer" />
          </el-form-item>
          <el-form-item label="所属项目：" prop="projectName" label-width="100px">
            <el-select v-model="prescriptionForm.projectName" class="el-select-y" filterable placeholder="请选择" @change="handleSelectProject">
              <el-option v-for="item in projectNameOptions" :key="item.id" :label="item.projectName" :value="item.projectId" />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库：" prop="warehouseId" label-width="100px">
            <el-select v-model="prescriptionForm.warehouseId" class="el-select-y" filterable placeholder="请选择" @change="handleSelectWarehouse">
              <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <p style="padding-left: 0;">挑选药品</p>
        <el-container class="choose">
          <el-aside width="195x">
            <LeftClassification :tabs-text="tabsText" @classificationClist="getClassificationId" />
          </el-aside>
          <el-main>
            <div>
              <el-input v-model="search" placeholder="请输入名称和拼音码" clearable style="width:30%;margin-bottom: 10px" @input="searchData" />
              <div class="box-show">
                <el-table ref="multipleTable" v-loading="loading" :data="tableData" border :row-class-name="tableColor" style="width: 100%" @select="handleSelect" @select-all="handleSelectAll">
                  <el-table-column label="名称" prop="name" :show-overflow-tooltip="true" />
                  <el-table-column prop="searchCode" label="拼音码" :show-overflow-tooltip="true" />
                  <el-table-column prop="spec" label="规则" :show-overflow-tooltip="true" />
                  <el-table-column prop="unit" label="单位" :show-overflow-tooltip="true" />
                  <el-table-column prop="sellPrice" label="售价" :show-overflow-tooltip="true" />
                  <el-table-column type="selection" label="操作" width="55" />
                </el-table>
              </div>
            </div>
          </el-main>
        </el-container>
      </div>
      <div class="box-show">
        <p>药品清单</p>
        <el-table :data="chargeTableData" border :row-class-name="tableColor">
          <el-table-column label="名称" prop="medicinesName" :show-overflow-tooltip="true" />
          <el-table-column label="规格" prop="medicinesSpec" :show-overflow-tooltip="true" />
          <el-table-column label="单位" prop="medicinesUnit" :show-overflow-tooltip="true" />
          <el-table-column label="用法" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dictionary-selector class="el-select-y" code="swan_department_ypyf" :value.sync="scope.row.usageMethod" />
            </template>
          </el-table-column>
          <el-table-column label="频率" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dictionary-selector class="el-select-y" code="swan_department_ypsypl" :value.sync="scope.row.frequency" />
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="price" :show-overflow-tooltip="true" />
          <el-table-column label="可用库存" prop="availableStock" :show-overflow-tooltip="true" />
          <el-table-column label="开单数量" min-width="100px" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.quantity" controls-position="right" :min="1" style="width: 80px;" @change="quantityChange" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="deleteBtn(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="poto">
        <p>
          <span class="spns">医嘱：</span>
          <span><el-input v-model="prescriptionForm.medicalAdvice" type="textarea" :rows="3" placeholder="请输入内容" /></span>
        </p>
        <div class="rightDiv">
          <p>总额：￥{{ amount?amount:0 }}</p><p>优惠：-￥0</p><p>合计：<span class="spn">￥{{ amount?amount:0 }}</span></p>
        </div>
        <el-row class="poto">
          <el-col :span="3">付款方式</el-col>
          <el-col :span="7">
            <el-radio v-model="paymentMethod" label="项目包含">项目包含（不需再次付款）</el-radio>
            <p><el-radio v-model="paymentMethod" label="额外付款">额外付款</el-radio></p>
          </el-col>
        </el-row>
      </div>
      <!-- <el-row type="flex" justify="center">
        <el-col :span="3">
          <el-button @click="submitForm">提交</el-button>
        </el-col>
        <el-col :span="3">
          <el-button @click="handleClose">取消</el-button>
        </el-col>
      </el-row> -->
    </Dialog>
  </div>
</template>
<script>
import Dialog from "@/components/Dialog/index";
import UserInfo from "@/components/UserInformation";
import LeftClassification from "@/components/leftClassification";
import { tableColor } from '@/utils/common.js';
export default {
  components: {
    Dialog,
    UserInfo,
    LeftClassification,
  },
  props: {
    reveal: {
      type: Boolean,
      default: false,
    },
    control: {
      type: Boolean,
      default: true,
    },
    selectedRow: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      tableColor,
      prescriptionForm: {},
      search: '',
      textarea: '',
      tabsBool: 1,
      tabsText: [
        { label: '药品', name: 'drugs' },
      ],
      tableData: [],
      chargeTableData: [],
      restaurants: [],
      projectNameOptions: [],
      warehouseList: [],
      searchVal: {},
      // selectedRows: [],
      amount: 0, // 总金额
      paymentMethod: "项目包含",
      loading: false,
      visible: false,
      title: '开处方',
      prescriptionFormRules: {
        customerName: [
          { required: true, message: "请选择顾客", trigger: "change" },
        ],
        warehouseId: [
          { required: true, message: "请选择仓库", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    chargeTableData: {
      handler(val) {
        if (val && val.length > 0) {
          val.forEach((item) => {
            item.medicinesName = item.name;
            item.medicinesSpec = item.spec;
            item.medicinesUnit = item.unit;
            item.price = item.sellPrice;
          });
        }
        this.quantityChange();
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    this.$emit('childMounted');
    this.loadAll();
    this.warehouseListHandle();
  },
  methods: {
    openDialog(row) {
      this.visible = true;
      this.prescriptionForm = row;
    },
    prescriptionBtn(row) {
      if (row && row.customerId) {
        this.prescriptionForm = row;
        this.getProjectName(row.customerId);
      }
      this.visible = true;
      this.warehouseListHandle();
    },
    async loadAll() {
      const res = await this.$api["reception/subscribe/findall"]();
      if (res.code === 200) {
        res.data.map((item) => {
          item.value = item.name;
        });
        this.restaurants = res.data;
      }
    },
    querySearch(queryString, cb) {
      console.log(queryString, cb);
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        if (restaurant.value) {
          return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
          );
        } else {
          return null;
        }
      };
    },
    handleSelectCustomer(item) {
      this.$set(this.prescriptionForm, 'customerName', item.name);
      this.$set(this.prescriptionForm, 'customerId', item.id);
      this.getProjectName(item.id);
    },
    // 顾客已购项目
    async getProjectName(id) {
      this.projectNameOptions = [];
      const res = await this.$api["reception/subscribe/deductionRecordLists"]({ customerId: id });
      if (res.code === 200) {
        this.projectNameOptions = res.data;
      }
    },
    handleSelectProject(id) {
      this.prescriptionForm.projectId = id;
      this.projectNameOptions.map(item => {
        if (item.projectId === id) {
          this.prescriptionForm.projectName = item.projectName;
        }
      });
    },
    handleSelectWarehouse(id) {
      this.prescriptionForm.warehouseId = id;
      this.warehouseList.map(item => {
        if (item.id === id) {
          this.prescriptionForm.warehouseName = item.name;
        }
      });
    },
    // 仓库
    warehouseListHandle() {
      this.warehouseList = [];
      const list = JSON.parse(localStorage.WARE_HOUSE);
      console.log(list);
      list.forEach(item => {
        if (item.grant.indexOf("前台仓库") > -1) {
          this.warehouseList.push(item);
        }
      });
      if (this.warehouseList.length > 0) this.$set(this.prescriptionForm, 'warehouseId', this.warehouseList[0].id);
    },
    submitForm() {
      this.$refs.prescriptionFormRef.validate(async(valid) => {
        if (valid) {
          if (this.paymentMethod) {
            this.prescriptionForm.paymentMethod = this.paymentMethod;
          }
          if (this.amount) {
            this.prescriptionForm.amount = this.amount;
          }
          this.loading = true;
          const res = await this.$api['department/order/addprescriptionlist']({ ...this.prescriptionForm, prescriptionListDetailsDtoList: this.chargeTableData });
          this.loading = false;
          console.log(res, 'success');
          if (res.code !== 200) return this.$message.error('添加处方失败!');
          this.$message.success('添加处方成功！');
          this.visible = false;
          this.$emit('success');
        }
      });
    },
    handleClose() {
      // this.selectedRows = [];
      this.chargeTableData = [];
      this.tableData = [];
      this.prescriptionForm.medicalAdvice = '';
      this.paymentMethod = "项目包含";
      this.$emit('componentResult', "close");
      this.visible = false;
      this.$refs.prescriptionFormRef.resetFields();
    },
    // 点击左侧的树状筛选表格数据
    async getClassificationId(val) {
      this.searchVal.productClassificationId = val.list.join(","); // 查询提交的产品分类id
      this.searchVal.warehouseId = this.prescriptionForm.warehouseId;
      const url = 'data/drugs/drugsList';
      const msg = '查询药品列表';
      this.loading = true;
      const res = await this.$api[url]({ query: { ...this.searchVal }});
      this.loading = false;
      if (res.code !== 200) return this.$message.error(msg + '失败!');
      this.tableDataList = res.data;
      this.tableData = JSON.parse(JSON.stringify(this.tableDataList));
      this.tableData.forEach(item => {
        this.$set(item, 'quantity', 1);
      });
      // this.$message.success(msg + '成功');
    },
    // 表格顶部的搜索框
    searchData(search) {
      if (search) {
        if (!this.tableDataList || this.tableDataList.length === 0) return;
        this.tableData = [];
        this.tableDataList.forEach((item) => {
          if (this.tabsBool === 1) {
            if (!item.name || !item.searchCode) return false;
            if (
              item.name.indexOf(search) > -1 || (item.searchCode && item.searchCode.indexOf(search) > -1)
            ) { this.tableData.push(item); }
          }
        });
      } else {
        this.tableData = JSON.parse(JSON.stringify(this.tableDataList));
      }
    },
    handleSelect(event, row) {
      let isExistence = false;
      this.chargeTableData.forEach((item, index) => {
        if (item.id === row.id) {
          isExistence = true;
          this.chargeTableData.splice(index, 1);
        }
      });
      if (!isExistence) {
        const json = JSON.parse(JSON.stringify(row));
        this.chargeTableData.push(json);
      }
    },
    handleSelectAll(selection) {
      if (selection.length > 0) {
        selection.forEach((item) => {
          let isExistence = false;
          this.chargeTableData.forEach((json) => {
            if (json.id === item.id) {
              isExistence = true;
            }
          });
          if (!isExistence) {
            const json = JSON.parse(JSON.stringify(item));
            this.$set(json, "discount", false);
            this.$set(json, "checkeds", true);
            this.chargeTableData.push(json);
          }
        });
      } else {
        this.tableData.forEach((item) => {
          this.chargeTableData.forEach((json, index) => {
            if (json.id === item.id) {
              this.chargeTableData.splice(index, 1);
              index--;
            }
          });
        });
      }
    },
    quantityChange() {
      let totalPrice = 0;
      this.chargeTableData.map(item => {
        totalPrice += item.price * item.quantity;
      });
      this.amount = totalPrice;
    },
    async deleteBtn(row) {
      const confirmResult = await this.$confirm('请确认是否取消?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      }
      for (var i = 0; i < this.chargeTableData.length; i++) {
        if (this.chargeTableData[i].id === row.id) {
          this.chargeTableData.splice(i, 1);
        }
      }
      this.tableData.map((vals) => {
        if (row.id === vals.id) {
          this.$refs.multipleTable.toggleRowSelection(vals, false);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.formStyles{
  .UserInfoCss{
    margin-bottom: 15px;
  }
 .el-select{
    width: 237.5px !important;
  }
}
.poto{
    margin-top: 30px;
    .spns{
    display: block;
    margin: 10px 0;
    }
    .rightDiv{
      float: right;
      overflow: auto;
        .spn{
    color: #ff6600;
  }
    }
  }
.choose{
  max-height: 300px;
  }
  .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  margin-bottom: 18px;
}
</style>
